/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package me.whily.hee.view.common;

import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.List;
//import javax.swing.ImageIcon;
//import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.MenuElement;
import me.whily.hee.model.entity.User;
import me.whily.hee.model.entity.Menu;
import me.whily.hee.model.service.MenuService;
import me.whily.hee.util.CacheUtil;
import me.whily.hee.util.Constant;
import me.whily.hee.view.components.ButtonTabComponent;
import org.apache.log4j.Logger;

/**
 * 主窗体
 * @author wanghy
 * @since 2015-05-23 16:53:27
 */
public class Main extends javax.swing.JFrame {
    Logger logger = Logger.getLogger(this.getClass());
    MenuService menuService = new MenuService();
    /**
     * Creates new form Main
     */
    public Main() {
        initComponents();
        initMenu();
        String title = "首页";
//        jTabbedPane1.add(title, new JLabel(new ImageIcon(getClass().getResource("/resource/images/Pig.gif"))));
    }
    
    /**
     * 初始化Tab组件
     * @param i 
     */
    private void initTabComponent(int i) {
        jTabbedPane1.setTabComponentAt(i,
                 new ButtonTabComponent(jTabbedPane1));
    }    
    
    /**
     * 新增tab页
     * @param title 名称
     * @param action 显示组件的路径
     */
    private void addTab(String title, String action) {
        if (jTabbedPane1.indexOfTab(title) == -1) {
            try {
                jTabbedPane1.addTab(title, (Component) Class.forName(action).newInstance());
                int selectedIndex = jTabbedPane1.getTabCount() - 1;
                initTabComponent(selectedIndex);
                jTabbedPane1.setSelectedIndex(selectedIndex);
            } catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) {
                logger.error("新增tab页时异常：", e);
            } catch (Exception e) {
                logger.error("新增tab页时异常：", e);
            } 
        }
    }
    
    /**
     * 
     */
    private void initMenu() {
        try {
//            User loginUser = (User)CacheUtil.cacheMap.get(Constant.LOGIN_USER);
//            jLabelLoginName.setText(loginUser.getUname());
//            List<Menu> menus = menuService.findByUserId(loginUser.getUid());
            List<Menu> menus = menuService.findByUserId("wanghy");
            for (Menu menu : menus) {
                if (menu.getMpid() == 0) {
                    JMenu jMenu = new JMenu(menu.getMname());
                    jMenu.setName(menu.getMid().toString());
                    jMenuBar1.add(jMenu);
                } else {
                    MenuElement[] subElements = jMenuBar1.getSubElements();
                    for (MenuElement subElement : subElements) {
                        JMenu jMenu1 = (JMenu) subElement;
                        if (menu.getMpid().equals(Integer.parseInt(jMenu1.getName()))) {
                            JMenuItem jMenuItem = new JMenuItem(menu.getMname());
                            jMenuItem.setName(menu.getMid().toString());
                            jMenuItem.setActionCommand(menu.getMname() + ":" + menu.getMaction());
                            jMenuItem.addActionListener(new ActionListener() {
                                @Override
                                public void actionPerformed(ActionEvent e) {
                                    String[] acs = e.getActionCommand().split(":");
                                    addTab(acs[0], acs[1]);
                                }
                            });
                            jMenu1.add(jMenuItem);
                            break;
                        }
                    }
                }
            }
        } catch (Exception ex) {
            logger.error("初始化菜单异常：", ex);
        }
    }
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jToolBar1 = new javax.swing.JToolBar();
        jPanel2 = new javax.swing.JPanel();
        jLabelLoginName = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jTabbedPane1 = new javax.swing.JTabbedPane();
        jMenuBar1 = new javax.swing.JMenuBar();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("HEE进销存系统");
        setExtendedState(6);
        setLocationByPlatform(true);

        jToolBar1.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
        jToolBar1.setFloatable(false);
        jToolBar1.setRollover(true);
        jToolBar1.setEnabled(false);

        jPanel2.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));

        jLabel2.setText("欢迎您，");

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
                .addContainerGap(244, Short.MAX_VALUE)
                .addComponent(jLabel2)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabelLoginName, javax.swing.GroupLayout.PREFERRED_SIZE, 63, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(37, 37, 37))
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addComponent(jLabelLoginName, javax.swing.GroupLayout.PREFERRED_SIZE, 15, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(0, 0, Short.MAX_VALUE))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jLabel2)
                .addContainerGap())
        );

        setJMenuBar(jMenuBar1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addComponent(jToolBar1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addComponent(jTabbedPane1)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jToolBar1, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jTabbedPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 234, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, 33, javax.swing.GroupLayout.PREFERRED_SIZE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(Main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Main().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabelLoginName;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JTabbedPane jTabbedPane1;
    private javax.swing.JToolBar jToolBar1;
    // End of variables declaration//GEN-END:variables
}
